from django.shortcuts import render, redirect
# 导包
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
# 导入类视图
from django.views import View

from app01.models import User, Category, Course
import json
from django.core.serializers import serialize
from .serializer import UserSer, CategorySer, CourseSer
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入加密库
import hashlib
# 导入redis
from redis import Redis
redis = Redis("localhost", 6379)

# 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io

import requests

# 导入上传文件夹配置
from mypro.settings import UPLOAD_ROOT
import os

# 但课程接口
class SingleCourse(APIView):

    def get(self, request):
        # 获取参数
        id = request.GET.get('id','')
        # 获取单课程
        course = Course.objects.filter(id=int(id)).first()
        # 序列化
        course_ser = CourseSer(course)
        # 返回结果
        return Response(course_ser.data)


# 课程列表
class CourseList(APIView):

    def get(self, request):
        # 当前页
        page = request.GET.get("page", 1)
        # 每页条数
        size = request.GET.get('size', 1)
        # 开始位置
        data_start = int(page)-1 * int(size)
        # 结束位置
        data_end = int(page) * int(size)

        # 获取课程列表
        clist = Course.objects.all()[data_start:data_end]
        # 获取总条数
        count = Course.objects.count()

        # 序列化
        clist_ser = CourseSer(clist, many=True)

        # 返回容器
        res = {}
        res['total'] = count
        res['data'] = clist_ser.data

        # 返回结果
        # return Response(res.data)
        return Response(res)



# 课程入库接口
class AddCourse(APIView):

    def get(self, request):
        # 接收参数
        title = request.GET.get('title', '')
        desc = request.GET.get('desc', '')
        category = request.GET.get('category', '')
        img = request.GET.get('img', '')
        uid = request.GET.get('uid', '')
        price = request.GET.get('price', '')
        # 查询分类
        cate = Category.objects.filter(name=category).first()
        # 排重操作
        course = Course.objects.filter(title=title).first()
        if course:
            res = {}
            res['code'] = 405
            res['message'] = '课程已经存在'
            return Response(res)

        # 进行入库逻辑
        course = Course(title=title, desc=desc, img=img, uid=int(uid), price=int(price), cid=int(cate.id))
        # 保存
        course.save()
        # 返回结果
        res = {}
        res['code'] = 200
        res['message'] = '添加课程成功'
        return Response(res)

# 定义课程分类接口
class Coursesave(APIView):

    def get(self, request):
        courses = Course.objects.all()
        # 注instance用于接受序列化的对象，many表示是queryset对象
        courses_ser = CourseSer(courses, many=True)
        return Response(courses_ser.data)


# 定义课程分类接口
class CategoryList(APIView):

    def get(self, request):
        cates = Category.objects.all()
        # 注instance用于接受序列化的对象，many表示是queryset对象
        cates_ser = CategorySer(cates, many=True)
        return Response(cates_ser.data)


# 定义文件上传类
class UploadFile(View):

    def post(self, request):
        img = request.FILES.get('file')
        # 建立文件流对象
        f = open(os.path.join(UPLOAD_ROOT, '', img.name), 'wb')

        # 写文件 遍历文件流
        for chunk in img.chunks():
            f.write(chunk)
        f.close()

        # 返回结果
        return HttpResponse(json.dumps({'filename': img.name}), content_type='application/json')


# 定义新浪微博回调方法
def weibo_back(request):
    # 获取新浪微博回调的code
    code = request.GET.get('code')
    # 微博认证地址
    access_token_url = "https://api.weibo.com/oauth2/access_token"
    # 发起http请求
    re_dict = requests.post(
        access_token_url,
        data={
            # app_id  应用id
            "client_id": '2636039333',
            # app_secret 密钥
            "client_secret": "4e2fbdb39432c31dc5c2f90be3afa5ce",
            # 授权类型 code
            "grant_type": "authorization_code",
            # code 参数
            "code": code,
            # 回调网址
            "redirect_uri": "http://127.0.0.1:8000/md_admin/weibo"
        }
    )
    # 打印数据
    re_dict = re_dict.text
    # 强转数据类型
    re_dict = eval(re_dict)

    # 判断是否用新浪微博账号登录过
    user = User.objects.filter(username=str(re_dict['uid'])).first()

    sina_id = ''
    user_id = ''
    if user:
        # 代表曾经登录并且生成过账号
        sina_id = user.username
        user_id = user.id
    else:
        # 自动创建账号
        user = User(username=str(re_dict['uid']), password=make_password(''), type=0)
        # 保存
        user.save()
        sina_id = str(re_dict['uid'])
        # 查询数据库的id
        user = User.objects.filter(username=str(re_dict['uid'])).first()
        user_id = user.id

    # 进行跳转
    return redirect("http://localhost:8080?sina_id=" + sina_id + "&uid=" + str(user_id))
    # return HttpResponse("test")


# 定义验证码类
class MyCode(View):

    # 定义随机取色方法
    def get_random_color(self):
        R = random.randrange(255)
        G = random.randrange(255)
        B = random.randrange(255)
        return (R, G, B)

    def get(self, request):
        # 定义画布
        img_size = (120, 50)
        # 定义图像 颜色种类，画布，背景颜色
        image = Image.new('RGB', img_size, 'white')
        # 定义画笔
        draw = ImageDraw.Draw(image, 'RGB')
        # 随机字符串组成
        source = '01234567890asdfgh'
        # 定义容器
        code_str = ''
        for i in range(4):
            # 取色
            text_color = self.get_random_color()
            # 获取一个字符串
            tmp_num = random.randrange(len(source))
            # 获取字符集
            random_str = source[tmp_num]
            # 将随机生成的字符串放入定义好的容器
            code_str += random_str
            # 将文字输入绘图
            draw.text((10 + 30 * i, 20), random_str, text_color)
        # 建立io文件流
        buf = io.BytesIO()
        # 保存内存中
        image.save(buf, 'png')
        # 将验证码放入redis
        redis.set('code', code_str)
        # 将验证码放入session
        # request.session['code'] = code_str
        print(request.session['code'])
        # 返回文件流图像
        return HttpResponse(buf.getvalue(), 'image/png')


# 加密方法
def make_password(mypass):
    # md5算法
    mypass = hashlib.md5()
    # 对字符串进行编译(加盐操作)
    mypass.update('123'.encode(encoding='utf-8'))
    # 返回密文
    return mypass.hexdigest()


# 登录接口
class Login(APIView):
    def post(self, request):
        # 接收参数
        username = request.POST.get('username', '未收到用户名')
        password = request.POST.get('password', '未收到密码')

        # 查询数据
        user = User.objects.filter(username=username, password=make_password(password)).first()

        if user:
            # 返回结果
            res = {}
            res['code'] = 200
            res['message'] = '登录成功'
            res['username'] = user.username
            return Response(res)
        else:
            res = {}
            res['code'] = 405
            res['message'] = '您的用户名或者密码错误'
            return Response(res)


# 注册接口
class Register(APIView):
    def get(self, request):

        # 接收参数
        username = request.GET.get('username', '未收到用户名')
        password = request.GET.get('password', '未收到密码')

        # 获取随机验证码
        code = request.GET.get('code', '未收到验证码')

        # 获取session中的验证码
        # mycode = request.session.get('code', None)
        # print(mycode)
        # 获取redis中的验证码
        mycode = redis.get('code')
        mycode = mycode.decode('utf-8')

        if code != mycode:
            res = {}
            res['code'] = 405
            res['message'] = '验证码输入错误'
            return Response(res)

        # 排重操作
        user = User.objects.filter(username=username).first()
        if user:
            res = {}
            res['code'] = 405
            res['message'] = '用户已经存在'
            return Response(res)

        # 进行入库逻辑 加密
        user = User(username=username, password=make_password(password), type=0)
        # 保存
        user.save()

        # 返回结果
        res = {}
        res['code'] = 200
        res['message'] = '注册成功'
        return Response(res)


def myindex(request):
    res = User.objects.all()
    mylist = json.loads(serialize('json', res, ensure_ascii=False))
    return JsonResponse(mylist, safe=False, json_dumps_params={'ensure_ascii': False})


class MyUser(APIView):
    def post(self, request):
        users = User.objects.all()
        # 注instance用于接受序列化的对象，many表示是queryset对象
        users_ser = UserSer(users, many=True)
        return Response(users_ser.data)


# 模板练习
def mytem(request):
    title = 'Hello Django'
    num = 100
    li = [1, 2, 3, 4, 5]
    dic = {'name': '123', 'age': 12}

    # 读库
    res = User.objects.all()

    return render(request, 'index.html', locals())
